import "./index.scss";
import React, { Component } from "react";
import services from "services";
import * as tools from "libs/tools";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import wxjssdk from "libs/wxjssdk";
import AppWakeup from "components/AppWake";
import Comments from "components/Comments";
import Modal from "components/Modal";
import Swiper from "swiper";
import "swiper/dist/css/swiper.css";

class Page extends Component {
  state = {
    comments: [],
    currentIndex: 1,
    commentsLoaded: false
	};

  componentDidMount() {
    this.fetchArticle();
	}

	componentWillUnmount() {
    this.mySwiper && this.mySwiper.destroy();
		this.shareTimer && clearInterval(this.shareTimer);
		this.player && this.player.dispose();
	}
	
	fetchArticle = () => {
    // 84 提问， 9 图片，16 视频，85 纯文字
    services.App.getUGCArticle({ id: this.props.match.params.id, uid: tools.getQueryStringObject().uid }).then(res => {
      let { code, data } = res.data;

      if (code !== 0) return this.setState({ notFound: true });

      this.setState({ article: data }, () => {
        this.initShare(data);

        if (!data.isquestion) {
          data.images.length && this.initSwiper();
          data.video.length && this.initVideo();
        }
      });
    });
  }

  initVideo = () => {
    this.player = videojs(document.querySelector('.video-js'), this.props, function onPlayerReady() {
    });
  }

  initShare = (data) => {
    window.setDetailShare = function () {
      wxjssdk.initShare(
        location.href.split('?')[0],
        data.content ? data.content.slice(0, 20) : '彩育发现里有我的笔记，是你感兴趣的',
        '彩育笔记，分享生活，一键提问',
        'https://jzimg.jzdoctor.com/ugc-share.jpg'
      );
    };

    window.setDetailShare();
    this.shareTimer = setInterval(window.setDetailShare, 800);
  }
  
  initSwiper = () => {
    this.mySwiper = new Swiper ('.swiper-container', {
			on: {
				transitionEnd: () => {
					this.setState({ currentIndex: this.mySwiper.realIndex+1 });
				}
			}
		});
  }

  toggleDownloadAppModal = visible => {
    this.setState({
      downloadAppModalVisible: visible
    });
  }

  render() {
    let { currentIndex, article, notFound, downloadAppModalVisible } = this.state;
    let appWakeUpProps = {};

    //  define app wakeup props
    if (article) {
      let path, action;

      if (article.isquestion) path = 'open_ugc_question';
      else if (article.video.length) path = 'open_ugc_video';
      else if (article.images.length) path = 'open_ugc_image';
      else path = 'open_ugc_text';

      action = path; //  action is same as path
      
      appWakeUpProps = {
        path,
        action,
        id: this.props.match.params.id,
        top: true
      };
    }
		
    return (
      <React.Fragment>
        {
          article && 
          <div className="page-ugc">
            <AppWakeup getInstance={instance => (this.appWakeUpInstance = instance)} {...appWakeUpProps} />

            <div className="ugc-hd">
              {
                article.video.length > 0 &&
                <div className="ugc-video">
                  <video id='my-video' className='video-js' controls preload='auto' data-setup='{}'>
                    <source src={article.video[0].file} type='video/mp4' />
                  </video>
                </div>
              }

              {/* swiper */}
              {
                !article.isquestion && article.images.length > 0 && (
                  <div className="ugc-large-images" onClick={this.toggleDownloadAppModal.bind(this, true)}>
                    <div className="swiper-container">
                      <div className="swiper-wrapper">
                        {article.images.map((image, index) => (
                        <div className="swiper-slide" key={index}>
                          <img src={`${image.file}?imageView2/1/w/750/h/750/q/75`} />
                        </div>	
                      ))}
                      </div>
                    </div>
                    <div className="ucg-large-images-counter">{currentIndex}/{article.images.length}</div>
                  </div>
                )
              }
              {/* end swiper */}

              <div className="ugc-meta">
                <span className="ugc-meta-date">{article.addtime}</span>
                { article.user && <span className="ugc-meta-author">{article.user.nickname}</span> }
              </div>

              {
                article.isquestion && article.content && (
                  <div className="ugc-title">
                    <span className="ugc-title-type">问题</span>
                    { article.content }
                  </div>
                )
              }
              
              { !article.isquestion && article.content && <div className="ugc-content">{article.content}</div> }

              {
                article.isquestion && article.images.length > 0 && (
                  <div className="ugc-images" onClick={this.toggleDownloadAppModal.bind(this, true)}>
                    {article.images.map((image, index) => (
                      <img src={`${image.file}?imageView2/1/w/440/h/440/q/75`} key={index} />
                    ))}
                  </div>
                )
              }

              { article.plate.map((tag, index) => <div className="ugc-tag" key={index}>{tag.name}</div>) }
            </div>

            <div className="ugc-bd">
              {
                article.isquestion && article.reply && (
                  <div className="answer">
                    <h2 className="answer-hd">专家回答</h2>
                    <div className="answer-bd">
                      <div className="answer-meta">
                        <div className="answer-meta-avatar"><img src={article.doctor.headimageurl}/></div>
                        <div className="answer-meta-bd">
                          <p className="answer-meta-name">{article.doctor.nickname}</p>
                          <p className="answer-meta-date">{article.replytime}</p>
                        </div>
                      </div>
                      <div className="answer-content">{article.reply}</div>
                    </div>
                  </div>
                )
              }

              <Comments 
                onCommentContainerClick={this.toggleDownloadAppModal.bind(this, true)} 
                api={services.App.getUGCArticleComments({ id: this.props.match.params.id })}
                thumbCount={article.thumbcount >> 0}
              />
            </div>
            
            <Modal
              title="继续操作需要下APP"
              visible={downloadAppModalVisible}
              footer={
                <React.Fragment>
                  <div className="modal-btn" onClick={this.toggleDownloadAppModal.bind(this, false)}>取消</div>
                  <div className="modal-btn" onClick={() => this.appWakeUpInstance.openApp()}>下载App</div>
                </React.Fragment>
              }
            ></Modal>
          </div>
        }
        { notFound && '哦..sorry..文章飘去其他星球了...' }
      </React.Fragment>
    );
  }
}

export default Page;
